package cn.com.shuyangyang.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

public class BaseUtil
{
	public static final boolean DEBUG = false;//开启debug
  public static boolean isSpace(Integer i)
  {
	if(null==i){
		return true;
	}
	if(i==0){
		return true;
	}
    return false;
  }
  public static String getFirstName(String checkStr){
		if(BaseUtil.isSpace(checkStr)){
			return "";
		}
		String value = "";
		//定义一个包含26个英文字母和阿拉伯数字的字符串
		for(int i=0;i<checkStr.length();i++){
			//返回指定索引处的 char 值
			char c=checkStr.charAt(i);
			//如果在该字符串找到该字符值
			if(!isSpace(c+"")){
				value+=c+"";
			}else{
				break;
			}
		}
		return value;
	}
  public static boolean isSpace(Float i)
  {
	if(null==i){
		return true;
	}
	if(i==0){
		return true;
	}
    return false;
  }
  /**
	 * 半角转换为全角
	 * 
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}


  public static boolean isSpace(Long i)
  {
	if(null==i){
		return true;
	}
	if(i==0){
		return true;
	}
    return false;
  }
  public static boolean isSpace(String str)
  {
	if(null==str){
		return true;
	}
	if(str.trim().equals("")){
		return true;
	}
    return false;
  }
  public static boolean isSpace(List list)
  {
	if(null==list){
		return true;
	}
	if(list.size()<1){
		return true;
	}
    return false;
  }
  public static boolean isSpace(String[] strArray)
  {
	if(null==strArray){
		return true;
	}
	if(strArray.length<1){
		return true;
	}
    return false;
  }
  
  public static boolean isAbcNumber(String checkStr){
		if("".equals(checkStr)){
			return false;
		}
		//定义一个包含26个英文字母和阿拉伯数字的字符串
		String strAbcNumber  ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		for(int i=0;i<checkStr.length();i++){
			//返回指定索引处的 char 值
			char c=checkStr.charAt(i);
			//如果在该字符串找到该字符值
			if(strAbcNumber.indexOf(c, 0)<0){
				return false;
			}
		}
		return true;
	}
  public static boolean isNumber(String checkStr){
		if("".equals(checkStr)){
			return false;
		}
		//定义一个包含26个英文字母和阿拉伯数字的字符串
		String strAbcNumber  ="0123456789";
		for(int i=0;i<checkStr.length();i++){
			//返回指定索引处的 char 值
			char c=checkStr.charAt(i);
			//如果在该字符串找到该字符值
			if(strAbcNumber.indexOf(c, 0)<0){
				return false;
			}
		}
		return true;
	}
  public static boolean isSpecial(String checkStr){
		//定义一个特殊字符字符串
		String strSpecial  =";<>*&!#(){}[]:‘“/^";
		for(int i=0;i<checkStr.length();i++){
			//返回指定索引处的 char 值
			char c=checkStr.charAt(i);
			//如果在该特殊字符串找到该字符值
			if(strSpecial.indexOf(c,0)>0){
				return true;
			}
		}
		return false;
	}
  
  public static List hashPull(List list,int max){
	  if(BaseUtil.isSpace(list)){
		  return list;
	  }
	  List rList = new ArrayList();
	  Hashtable <String,   Integer>   ht   =   new   Hashtable <String,   Integer> ();
	  Object[]   harrTmp= list.toArray();
	  String[]   harr = new String[harrTmp.length] ;
	  for(int i = 0;i<harrTmp.length;i++){
			 harr[i]=harrTmp[i].toString();
		 }
	  int   fre;     /*统计词频*/ 
	                                    /*填充hash表，重复出现的单词词频累加*/
	  for(int   i=0;i <harr.length;i++){
		  if(!ht.containsKey(harr[i])){
			  ht.put(harr[i],   1);
		  }
		  else{
			  fre=(Integer)(ht.get(harr[i]));
			  fre+=1;
			  ht.remove(harr[i]);
			  ht.put(harr[i],   fre);
		  }
	  }
	  /*调用getSortedHashtableByValue方法对词频排序*/
      Map.Entry[]   set   =   getSortedHashtableByValue(ht);
     if(set.length<max){
    	  max = set.length;
      }
      for   (int   i   =   0;   i   < max  ;   i++)   {
    	  rList.add(set[i].getKey().toString()); 
      }
      return rList;
  }
  private static Map.Entry[] getSortedHashtableByValue(Hashtable   h)   {
          Set   set   =   h.entrySet();
          Map.Entry[]   entries   =   (Map.Entry[])   set.toArray(new   Map.Entry[set.size()]);
          Arrays.sort(entries,   new   Comparator()   {
              public   int   compare(final   Object   arg0,   final   Object   arg1)   {
                  final   int   key1   =   Integer.parseInt(((Map.Entry)   arg0).getValue()
                          .toString());
                  final   int   key2   =   Integer.parseInt(((Map.Entry)   arg1).getValue()
                          .toString());
                  return   ((Comparable)   key2).compareTo(key1);
              }
          });
          return   entries;
  }
  /**
   * 统计给定字符串的字数（英文字符或字母算半个字）
   * @param detail
   * @return int 字符串字数
   * @author lydia
   * @date 2012-07-25
   */
  public static int getLength(String detail){
	  int len = detail.length();
	  int myLen =0;
	  for(int i=0;i<len && myLen<=280;i++){
		if(detail.charAt(i)>0 && detail.charAt(i)<128){
			myLen++;
		}else{
			myLen+=2;
		}  
	  }
	  BigDecimal b = new BigDecimal(myLen);
	  return b.divide(new BigDecimal(2),BigDecimal.ROUND_HALF_UP).intValue();
  }
	/*
	 * 截取内容(将转帖中的图片删掉在动态中显示)
	 * @param String content:内容
	 * @return String :截取后的内容
	 * @author 朱海勇
	 * @date 创建日期 2009-12-14
	 */
public static String cutContent(String content,int count){
	   String temp=content.trim();
	   try{
	     	 if(null==content||"".equals(content)){
	     		 return "...";
	     	 }
	     	 temp=content.trim().replace("&nbsp;", "");
	     	 if(temp.indexOf('<',0)>=0){
	     		 int start=temp.lastIndexOf('<');
	     		 int end=temp.lastIndexOf('>');
	     		 String come=temp.substring(0, start);
	     		 if(end<start){
	     			String to=temp.substring(start+1,temp.length());
	    			return cutContent(come+"&lt;"+to,count);
	    		 }
	     		 String too=temp.substring(end+1,temp.length());
	     		 return cutContent(come+too,count);
	     	 }
	     	if(temp.contains("[")){
		 		 for(int i=65;i<=96;i++){
		 			 if(temp.contains("[/"+i+"]")){
		 				temp = temp.replace("[/"+i+"]", "");
		 			 }
		 		 }
			 }
	     	if(temp.length()<=count){
	     		 return temp;
	     	 }else{
	     		 return temp.substring(0,count)+"...";
	     	 }
		 }catch(Exception e){
		 }
		 return temp;
    }
   public static String cutContent(String content){
   	   String temp=content.trim().replace("&nbsp;", "");
	   try{
	     	 if(null==content||"".equals(content)){
	     		 return "";
	     	 }
	     	 if(temp.indexOf('<',0)>=0){
	     		 int start=temp.lastIndexOf('<');
	     		 int end=temp.lastIndexOf('>');
	     		 String come=temp.substring(0, start);
	     		 if(end<start){
	     			String to=temp.substring(start+1,temp.length());
	    			return cutContent(come+"&lt;"+to);
	    		 }
	     		 String too=temp.substring(end+1,temp.length());
	     		 return cutContent(come+too);
	     	 }
	     	 return temp;
		 }catch(Exception e){
		 }
			 return temp;
    }
   public static String cutContentSize(String content,int count){
	   try{

	     	 if(null==content||"".equals(content)){
	     		 return "";
	     	 }
	     	 String temp=content.trim().replace("&nbsp;", "");
	     	 if(temp.length()<=count){
	     		 return temp;
	     	 }else{
	     		 return temp.substring(0,count-1)+"..";
	     	 }
		 }catch(Exception e){
		 }
		 return "";
   }
   public static int fuHaoCount(String checkStr){
	    int count = 0;
		//定义一个包含26个英文字母和阿拉伯数字的字符串
		String strAbcNumber  ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz，。！.、：；;!,.";
		for(int i=0;i<checkStr.length();i++){
			//返回指定索引处的 char 值
			char c=checkStr.charAt(i);
			//如果在该字符串找到该字符值
			if(strAbcNumber.indexOf(c, 0)<0){
				count++;
			}
		}
		return count;
	}
   public static String getparam(String param){
	   if(null==param){
		   return "";
	   }
	   if(param.indexOf(',')>-1){
		   String[] paramArr = param.split(",");
		   for(int i=0;i<paramArr.length;i++){
			   if(!paramArr[i].equals("")){
				   return paramArr[i];
			   }
		   }
	   }else{
		   return param;
	   }
	   return ""; 
   }
   /**
    * 取得BMI
    * @param weight 体重KG
    * @param height 身高CM
    * @return
    */
   public static float getBMI(float weight,float height){
	   return weight/(height/100)/(height/100); 
   }
   
   public static List  getparamList(String param1,String param2,List list){
	   String[] strArr = new String[2];
	   strArr[0]=param1;
	   strArr[1]=param2;
	   list.add(strArr);
	   return list;
   }
   
   /**
    * 取得一个估算的百分比
    * @param weight 体重KG
    * @param height 身高CM
    * @return
    */
   public static String getPer(int value){
	   if(value<10){
		   return "0%";
	   }else if(value>=10&&value<20){
		   return "1%";
	   }else if(value>=20&&value<30){
		   return "3%";
	   }else if(value>=30&&value<40){
		   return "6%";
	   }else if(value>=30&&value<40){
		   return (10+(value-30))+"%";
	   }else if(value>=40&&value<50){
		   return (20+(value-40))+"%";
	   }else if(value>=50&&value<60){
		   int i = value-50;
		   return (30+(i+1)*2) +"%"; 
	   }else if(value>=60&&value<70){
		   int i = value-60;
		   return (50+(i+1)*3) +"%"; 
	   }else if(value>=70&&value<80){
		   int i = value-70;
		   return (80+i) +"%"; 
	   }else if(value>=80&&value<90){
		   int i = value-80;
		   return (90+i/2) +"%"; 
	   }else if(value>=90&&value<100){
		   int i = value-90;
		   return (95+i/2) +"%"; 
	   }else if(value>=90&&value<100){
		   return "99.9%"; 
	   }
	   return "50%"; 
   }
   
   //共同方法
   public static String cutFloat(String str){
		 if(null==str||""==str){
           return "0";
		 }
         if(str.indexOf('.')<0){
            return str;
         }
         str=str.substring(0,str.indexOf('.'));
         return str;
   }
   //共同方法
   public static float cutFloat1(Float f){
		 if(null==f||0==f){
           return 0f;
		 }
        return (float)(Math.round(f*10))/10;
   }
   //共同方法
   public static float cutFloat2(Float f){
		 if(null==f||0==f){
           return 0f;
		 }
        return (float)(Math.round(f*100))/100;
   }
 //共同方法
   public static float cutFloat6(Float f){
		 if(null==f||0==f){
           return 0f;
		 }
        return (float)(Math.round(f*1000000))/1000000;
   }
   
   public static boolean sql_inj(String str)
   {
	   if(isSpace(str)){
		   return false;
	   }
	   String inj_str = "and&&exec&&insert&&select&&delete&&update&&count&&chr&&mid&&master&&truncate&&char&&declare&&database&&drop";
	   String inj_stra[] = inj_str.split("&&");
	   for (int i=0 ; i <inj_stra.length ; i++ )
	   {
		   if (str.indexOf(inj_stra[i])>=0)
		
		   {
			   return true;
		   }
	   }
	   return false;
   }
   public static String getrandom(long size,int count)
   {
	   String returnStr = "";
	   if(size<=0){
		   return returnStr;
	   }
	   try{
		   for(int i=0;i<count;i++){
			   long pos = ((int)(Math.random()*1000))%size;
			   if(i==0){
				   if(pos==0){
					   pos =1;
				   }
			   }
			   returnStr+=pos;
		   }
	   }catch(Exception e){
	   }
	   return returnStr;
   }
   public static String getPicture(String detail)
   {
	   String pictureSrc ="";
	   if(!BaseUtil.isSpace(detail)){
		   try{
			   	 String  tmp  = detail.replace("this.src", "");
			   	 if(tmp.contains("<img")){
			   		String tmp1 = tmp.substring(tmp.indexOf("<img"),tmp.length());
			   		if(tmp1.contains(">")){
					 String tmp2 = tmp1.substring(0,tmp1.indexOf(">")+1);
					 while(tmp2.contains("webEdit")||tmp2.contains("webbox")){
						 tmp1 = tmp1.replace(tmp2, "");
						 if(tmp1.contains("<img")){
							 tmp1 = tmp1.substring(tmp1.indexOf("<img"),tmp1.length());
							 tmp2 = tmp1.substring(0,tmp1.indexOf(">")+1);
						 }else{
							 return "";
						 }
					 }
					 tmp2 = tmp2.substring(tmp2.indexOf("src"),tmp2.length());
					 pictureSrc = tmp2.substring(tmp2.indexOf("\"")+1,tmp2.lastIndexOf("\""));
			   		}
			   	 }
			 }catch(Exception e){
				 e.printStackTrace();
			 }
			 
		   if(pictureSrc.contains("\"")){
			   pictureSrc=pictureSrc.substring(0, pictureSrc.indexOf("\""));
		   }
	   }
	   return pictureSrc;
   }
   
   
   public static void main(String[] args) {
	   String str="asdfasdfasdfasdf<img border=\"0\" alt=\"\" src=\"http://www.101care.com/webbox/plugins/emoticons/13.gif\"/>asdfasdfasdfasdfasdf";
	   System.out.println(getPicture(str));
   }
   public static String getTitle(String detail)
   {
	   String title ="";
	   int pin = detail.indexOf("#");
	   if(pin>-1&&detail.length()>pin+1){
		   int pos =detail.substring(pin+1,detail.length()).indexOf("#");
		   if(pos>0){
			   title=detail.substring(pin+1,pos+1+pin);
		   }
	   }
	   title=cutContent(title);
	   if(title.length()<21){
		   return title;
	   }
	   return "";
   }
   public static float[] getSortDesc(float[] array)
   {
	   for(int i=0;i<array.length;i++){
		   for(int j=array.length-1;j>i;j--){
			   if(array[j-1]<array[j]){
				   float tmp=array[j];
				   array[j]=array[j-1];
				   array[j-1]=tmp; 
			   }
		   }
	   }
	   return array;
   }
   
   
   public static List getIntList(int intValue){
	   List intList=new ArrayList();
	   for(int i=0;i<intValue;i++){
		   intList.add(i);
	   }
	   return intList;
   }
  
   public static String cutContent(String content,String startStr,String endStr){
	   try{
	     	 String temp=content.trim();
	     	 if(temp.indexOf(startStr,0)>=0){
	     		 int start=temp.indexOf(startStr);
	     		 String come=temp.substring(0, start);
	     		 String to=temp.substring(start+startStr.length(),temp.length());
	     		 int end=to.indexOf(endStr);
	     		 String too=to.substring(end+endStr.length(),to.length());
	     		 if(startStr.equals("<div")){
	     			return cutContent(come+"<br/>"+too,startStr,endStr);
	     		 }else{
	     			return cutContent(come+too,startStr,endStr);
	     		 }
	     	 }
	     	 return temp;
		 }catch(Exception e){
		 }
		 return content;
    }
   /**
    * 洗牌算法，取随机数
    * @param count
    * @return
    */
   public static String getRandom(int count){
	    String str = "";
	    String[] strArr = new  String[count];
	    for(int i = 0;i<count;i++){
	    	strArr[i]=(i+1)+"";
	    }
	    for(int k=0;k<count;k++){
	    	for(int i = 0;i<count;i++){
		    	int j = ((int)(Math.random()*10000))%count;
		    	String tmp = strArr[i];
		    	strArr[i] = strArr[j];
		    	strArr[j] = tmp;
		    }
	    }
	    for(int i = 0;i<count;i++){
	    	str+=strArr[i]+",";
	    }
		return str;
   }
   public static String getHTML(String url) throws IOException{
		String   sTotalString   =   "";
		if(!BaseUtil.isSpace(url)){
			java.net.URL l_url = null;
			l_url = new   java.net.URL(url);
	         java.net.HttpURLConnection   l_connection   =   (java.net.HttpURLConnection)   l_url.openConnection();
	         java.io.BufferedReader   l_reader   =   new   java.io.BufferedReader(new   java.io.InputStreamReader(l_connection.getInputStream()));
	         String   sCurrentLine   =   " ";
			 while   ((sCurrentLine   =   l_reader.readLine())   !=   null)
			 {
			         sTotalString+=sCurrentLine;
			 }
		}
		
		return sTotalString;
	}
   public static String getHTML1(String url) throws IOException{
		String   sTotalString   =   "";
		if(!BaseUtil.isSpace(url)){
			URLConnection uc = new URL(url).openConnection();
                uc.setConnectTimeout(10000);
                uc.setDoOutput(true);
                BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
                
                sTotalString = uncompress(in,"UTF-8");
		}
		
		return sTotalString;
	}

   public static String convertStreamToString(InputStream is) {

		StringBuilder sb1 = new StringBuilder();

		// 使用这个来读

		InputStreamReader inputStreamReader = new InputStreamReader(
				is, Charset.forName("utf-8"));

		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String line = null;
		try {
			while ((line = bufferedReader.readLine()) != null) {
				sb1.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb1.toString();
	}
   public static String convertStreamToStringZip(InputStream is) {

		StringBuilder sb1 = new StringBuilder();

		// 使用这个来读
		GZIPInputStream gzipInputStream = null;
		try {
			gzipInputStream = new GZIPInputStream(is);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		InputStreamReader inputStreamReader = new InputStreamReader(
				gzipInputStream, Charset.forName("utf-8"));

		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String line = null;
		try {
			while ((line = bufferedReader.readLine()) != null) {
				sb1.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb1.toString();
	}
   public static String uncompress(BufferedInputStream in,String charset) {
	   try {
	      GZIPInputStream gInputStream = new GZIPInputStream(in);
	      byte[] by = new byte[1024];
	      StringBuffer strBuffer = new StringBuffer();
	      int len = 0;
	      while ((len = gInputStream.read(by)) != -1) {
	       strBuffer.append( new String(by, 0, len,charset) );
	      }
	      return strBuffer.toString();
	   } catch (IOException e) {
	      e.printStackTrace();
	   }
	   return null;
	   }
   /**
    * 取得暗号化手机号
    * @param phoneNo
    * @return
    */
   public static String encodePhoneNo(String phoneNo){
	   if(!BaseUtil.isSpace(phoneNo)){
		   if(phoneNo.length()==11){
			   String encodeStr = phoneNo.substring(3, 9);
			   return phoneNo.replace(encodeStr, "******");
		   }else{
			   //用于暗号化激活卡号
			   if(phoneNo.length()==16){
				   String encodeStr = phoneNo.substring(3, 12);
				   return phoneNo.replace(encodeStr, "******");
			   }
		   }
	   }
	   return  "";
   }
   /**
    * 取得暗号化手机号替代4位
    * @param phoneNo
    * @return
    */
   public static String encodePhoneNum(String phoneNo){
	   if(!BaseUtil.isSpace(phoneNo)){
		   if(phoneNo.length()==11){
			   String encodeStr =phoneNo.substring(0, 3)+"****"+ phoneNo.substring(7, 11) ;
			   return encodeStr;
		   }
	   }
	   return  "";
   }
   /**
    * 身份证号处理
    * @param code
    * @return
    */
   public static String encodeUserCode(String code){
	   if(!BaseUtil.isSpace(code)){
		   if(code.length()==18){
			   String encodeStr = "******"+code.substring(6, 14)+"****";
			   return encodeStr;
		   }
	   }
	   return  "";
   }
   /**
	 *  年龄阶段
	 * @return
	 */
   public static Map<Integer, String> getPhases(){
	   Map<Integer,String> PHASES = new HashMap<Integer,String>();
		int k = 0;
		for(int i = 0;i<=95;i=i+5){
			PHASES.put(k++, i+"-"+(i+4));
		}
		return PHASES;
	}
   //计算距离
   public static long getDistance(long stepNum){
		return (long)(60l * stepNum/1000l/100l);
	}
   
   /*public static String getHtmlProxy1(String url) throws IOException{
	   Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.199.1", 80)); 
		String   sTotalString   =   "";
		if(!BaseUtil.isSpace(url)){
			java.net.URL l_url = null;
			l_url = new   java.net.URL(url);
	         java.net.HttpURLConnection   l_connection   =   (java.net.HttpURLConnection)   l_url.openConnection(proxy);
	         java.io.BufferedReader   l_reader   =   new   java.io.BufferedReader(new   java.io.InputStreamReader(l_connection.getInputStream()));
	         String   sCurrentLine   =   " ";
			 while   ((sCurrentLine   =   l_reader.readLine())   !=   null)
			 {
			         sTotalString+=sCurrentLine;
			 }
		}
		
		return sTotalString;
	}
  public static String getHtmlProxyPress1(String url) throws IOException{
	  Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.199.1", 80)); 
		String   sTotalString   =   "";
		if(!BaseUtil.isSpace(url)){
			URLConnection uc = new URL(url).openConnection(proxy);
               uc.setConnectTimeout(10000);
               uc.setDoOutput(true);
               BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
               
               sTotalString = uncompress(in,"UTF-8");
		}
		
		return sTotalString;
	}*/
}